package pers.nickerg.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JdbcUtil {
    public static Connection getConnection(Properties properties) throws Exception {

        // 1. 准备获取连接的 4 个字符串: user, password, url, jdbcDriver
        String user = properties.getProperty("jdbc.userName");
        String password = properties.getProperty("jdbc.password");
        String url = properties.getProperty("jdbc.url");
        String jdbcDriver = properties.getProperty("jdbc.driverClassName");

        // 2. 加载驱动: Class.forName(driverClass)  
        Class.forName(jdbcDriver);

        // 3.获取数据库连接  
        Connection connection = DriverManager.getConnection(url, user, password);
        return connection;
    }

    public static Properties getProperties(String jdbcProperties) throws IOException {
        Properties properties = new Properties();
        InputStream inStream = JdbcUtil.class.getClassLoader().getResourceAsStream(jdbcProperties);
        properties.load(inStream);
        return properties;
    }

    public static void releaseDB(PreparedStatement ps) {
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void releaseDB(ResultSet resultSet, Statement statement, Connection connection) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
} 